package com.todo.utils;

import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.util.LinkedMultiValueMap;

import com.todo.config.SmsConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 短信发送工具类
 * 封装linxiao短信接口
 */
@Component
public class SmsUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(SmsUtil.class);
    
    private final RestTemplate restTemplate;
    private final SmsConfig smsConfig;
    
    public SmsUtil(RestTemplate restTemplate, SmsConfig smsConfig) {
        this.restTemplate = restTemplate;
        this.smsConfig = smsConfig;
    }
    
    /**
     * 发送短信（使用默认配置）
     * @param mobile 手机号
     * @param content 短信内容
     * @return 发送结果
     */
    public SmsResult sendSms(String mobile, String content) {
        return sendSms(mobile, content, smsConfig.getLinxiao().getPartnerId(), smsConfig.getLinxiao().getProduct());
    }
    
    /**
     * 发送短信（完整参数）
     * @param mobile 手机号
     * @param content 短信内容
     * @param partnerId 合作伙伴ID
     * @param product 产品标签
     * @return 发送结果
     */
    public SmsResult sendSms(String mobile, String content, String partnerId, String product) {
        try {
            // 检查短信服务是否启用
            if (!smsConfig.getLinxiao().isEnabled()) {
                logger.warn("短信服务已禁用，跳过发送");
                return SmsResult.failure("短信服务已禁用");
            }
            
            // 参数验证
            if (mobile == null || mobile.trim().isEmpty()) {
                return SmsResult.failure("手机号不能为空");
            }
            if (content == null || content.trim().isEmpty()) {
                return SmsResult.failure("短信内容不能为空");
            }
            if (!isValidMobile(mobile)) {
                return SmsResult.failure("手机号格式不正确");
            }
            
            logger.info("开始发送短信，手机号：{}，内容长度：{}", mobile, content.length());
            
            // 构建POST表单数据
            MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
            formData.add("mobile", mobile);
            formData.add("content", content);
            formData.add("dock", smsConfig.getLinxiao().getDock());
            formData.add("partner_id", partnerId);
            formData.add("product", product);
            
            logger.debug("短信发送请求数据：{}", formData);
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            
            // 创建请求实体
            HttpEntity<MultiValueMap<String, String>> entity = 
                new HttpEntity<>(formData, headers);
            
            // 发送POST请求
            String response = restTemplate.postForObject(smsConfig.getLinxiao().getApiUrl(), entity, String.class);
            
            logger.info("短信发送响应：{}", response);
            
            // 解析响应结果
            return parseResponse(response);
            
        } catch (Exception e) {
            logger.error("发送短信异常，手机号：{}，错误信息：{}", mobile, e.getMessage(), e);
            return SmsResult.failure("发送短信失败：" + e.getMessage());
        }
    }
    
    /**
     * 发送验证码短信
     * @param mobile 手机号
     * @param code 验证码
     * @return 发送结果
     */
    public SmsResult sendVerificationCode(String mobile, String code) {
        String content = String.format("您的验证码是：%s，请在5分钟内使用，请勿泄露给他人。", code);
        return sendSms(mobile, content);
    }
    

    
    /**
     * 解析API响应结果
     */
    private SmsResult parseResponse(String response) {
        if (response == null || response.trim().isEmpty()) {
            return SmsResult.failure("短信接口返回空响应");
        }
        
        // 根据实际的API响应格式来解析
        // 这里需要根据linxiao短信接口的实际响应格式来调整
        if (response.contains("success") || response.contains("成功")) {
            return SmsResult.success("短信发送成功");
        } else {
            return SmsResult.failure("短信发送失败：" + response);
        }
    }
    
    /**
     * 验证手机号格式
     */
    private boolean isValidMobile(String mobile) {
        if (mobile == null) {
            return false;
        }
        // 简单的手机号格式验证（11位数字，1开头）
        return mobile.matches("^1[3-9]\\d{9}$");
    }
    
    /**
     * 短信发送结果封装类
     */
    public static class SmsResult {
        private boolean success;
        private String message;
        private String code;
        private Map<String, Object> data;
        
        private SmsResult(boolean success, String message) {
            this.success = success;
            this.message = message;
            this.data = new HashMap<>();
        }
        
        public static SmsResult success(String message) {
            return new SmsResult(true, message);
        }
        
        public static SmsResult failure(String message) {
            return new SmsResult(false, message);
        }
        
        // Getters and Setters
        public boolean isSuccess() {
            return success;
        }
        
        public void setSuccess(boolean success) {
            this.success = success;
        }
        
        public String getMessage() {
            return message;
        }
        
        public void setMessage(String message) {
            this.message = message;
        }
        
        public String getCode() {
            return code;
        }
        
        public void setCode(String code) {
            this.code = code;
        }
        
        public Map<String, Object> getData() {
            return data;
        }
        
        public void setData(Map<String, Object> data) {
            this.data = data;
        }
        
        public SmsResult addData(String key, Object value) {
            this.data.put(key, value);
            return this;
        }
        
        @Override
        public String toString() {
            return "SmsResult{" +
                    "success=" + success +
                    ", message='" + message + '\'' +
                    ", code='" + code + '\'' +
                    ", data=" + data +
                    '}';
        }
    }
} 